package jdec.jdt.ls.decompiler.common.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class FileUtil {

	public static String getContent(File file) {
		if (file == null || !file.exists())
			return null;
		try (InputStream is = new BufferedInputStream(new FileInputStream(file));
				ByteArrayOutputStream out = new ByteArrayOutputStream(4096)) {
			byte[] tmp = new byte[4096];
			while (true) {
				int r = is.read(tmp);
				if (r == -1)
					break;
				out.write(tmp, 0, r);
			}
			byte[] bytes = out.toByteArray();
			String content = new String(bytes);
			return content.trim();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getContent(File file, String enconding) {
		if (file == null || !file.exists())
			return null;
		try (InputStream is = new BufferedInputStream(new FileInputStream(file));
				ByteArrayOutputStream out = new ByteArrayOutputStream(4096)) {
			byte[] tmp = new byte[4096];
			while (true) {
				int r = is.read(tmp);
				if (r == -1)
					break;
				out.write(tmp, 0, r);
			}
			byte[] bytes = out.toByteArray();
			String content = new String(bytes, enconding);
			return content.trim();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void deltree(File root) {
		if (root == null || !root.exists()) {
			return;
		}

		if (root.isFile()) {
			root.delete();
			return;
		}

		File[] children = root.listFiles();
		if (children != null) {
			for (int i = 0; i < children.length; i++) {
				deltree(children[i]);
			}
		}

		root.delete();
	}
}
